const { ipcMain } = require('electron');
const path = require('node:path');
const fs = require('fs');

function setupDesktopBackground() {
    ipcMain.handle('setup_desktop', async (_event, _image_name, _) => {
        let imagePath = _image_name;

        //1, 检查传入的路径是否有效
        const fileExists = (filePath) => {
            return fs.promises.access(filePath, fs.constants.F_OK)
                .then(() => true)
                .catch(() => false);
        };


        //2, 如果传入路径无效，尝试拼接路径
        if (!(await fileExists(imagePath))) {
            if (process.env.NODE_ENV === 'production') {
                imagePath = path.join(process.resourcesPath, 'build', _image_name);
            } else {
                imagePath = path.join(__dirname, '../../build', _image_name);
            }
        }

        //3, 写入文件
        try {
            const wallpaper = await import('wallpaper');
            await wallpaper.setWallpaper(imagePath);
            return '说你爱我';
        } catch (error) {
            console.log(`error : ${error.message}`);
            return `error:${error.message}`;
        }
    });
}

module.exports = { setupDesktopBackground };